import {BasicColumn} from '/@/components/Table';
import {FormSchema} from '/@/components/Table';
import { rules} from '/@/utils/helper/validator';
import { render } from '/@/utils/common/renderUtils';
import { getDepartName, queryAllTreeListByPid } from './HealthDisease.api';
import { defHttp } from '/@/utils/http/axios';

// 全局变量存储项目组树形数据，用于查找节点名称
let globalProjectTreeData: any[] = [];
//列表数据
export const columns: BasicColumn[] = [
   {
    title: '身份证',
    align:"center",
    dataIndex: 'idNumber'
   },
   {
    title: '医院',
    align:"center",
    dataIndex: 'hospital_dictText'
   },
   {
    title: '医院ID',
    align:"center",
    dataIndex: 'hospital_id',
    customRender: ({ text }) => {
      // 使用字典渲染医院名称，如果后端提供了 hospital_id_dictText 会自动使用
      return render.renderDict(text, 'nurse_hospital,name,id') || text || '-';
    },
   },
   {
    title: '项目组id',
    align:"center",
    dataIndex: 'projectid',
    width: 200
   },
   {
    title: '项目组名字',
    align:"center",
    dataIndex: 'projectname'
   },
   {
    title: '疾病名字',
    align:"center",
    dataIndex: 'name'
   },
   {
    title: '疾病种类',
    align:"center",
    dataIndex: 'type'
   },
];
//查询数据
export const searchFormSchema: FormSchema[] = [
];
//表单数据
export const formSchema: FormSchema[] = [
  {
    label: '身份证',
    field: 'idNumber',
    component: 'Input',
  },
  {
    label: '医院',
    field: 'hospital',
    component: 'ApiSelect',
    componentProps: ({ formActionType, formModel }) => {
      return {
        api: async () => {
          const result = await defHttp.get({
            url: '/nurse_hospital/nurseHospital/rootList',
            params: {
              pageNo: 1,
              pageSize: 9999,
            },
          });
          if (result && result.records && Array.isArray(result.records)) {
            return result.records.map((item) => ({
              label: item.name,
              value: item.id,
              sysOrgCode: item.sysOrgCode,
            }));
          }
          return [];
        },
        labelField: 'label',
        valueField: 'value',
        placeholder: '请选择或搜索医院',
        showSearch: true,
        filterOption: (input, option) => {
          return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
        },
        allowClear: true,
        getPopupContainer: () => document.body,
        dropdownStyle: { zIndex: 9999 },
        onChange: async (value, option) => {
          formActionType.setFieldsValue({ 
            projectid: undefined,
            projectname: undefined,
          });
          
          if (!value || !option || !option.sysOrgCode) {
            formActionType.updateSchema([
              {
                field: 'projectid',
                componentProps: {
                  treeData: [],
                  disabled: true,
                  placeholder: '请先选择医院',
                },
              }
            ]);
            return;
          }

          try {
            const departResult = await getDepartName({ orgCode: option.sysOrgCode });

            if (departResult && departResult.id) {
              const treeResult = await queryAllTreeListByPid({ pid: departResult.id });
              const treeData = convertToTreeData(treeResult || []);
              globalProjectTreeData = treeData;

              formActionType.updateSchema([
                {
                  field: 'projectid',
                  componentProps: {
                    treeData: treeData,
                    disabled: false,
                    placeholder: '请选择项目组',
                  },
                }
              ]);
            }
          } catch (error) {
            // 加载失败
          }
        }
      };
    },
  },
  {
    label: '医院ID',
    field: 'hospital_id',
    component: 'ApiSelect',
    componentProps: ({ formActionType, formModel }) => {
      return {
        api: async () => {
          // 获取全部医院，使用更大的 pageSize 确保获取所有数据
          const result = await defHttp.get({
            url: '/nurse_hospital/nurseHospital/rootList',
            params: {
              pageNo: 1,
              pageSize: 99999,
            },
          });
          if (result && result.records && Array.isArray(result.records)) {
            return result.records.map((item) => ({
              label: item.name,
              value: item.id,
            }));
          }
          return [];
        },
        labelField: 'label',
        valueField: 'value',
        placeholder: '请选择或搜索医院',
        showSearch: true,
        filterOption: (input, option) => {
          return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
        },
        allowClear: true,
        getPopupContainer: () => document.body,
        dropdownStyle: { zIndex: 9999 },
      };
    },
  },
  {
    label: '项目组id',
    field: 'projectid',
    component: 'TreeSelect',
    componentProps: ({ formModel, formActionType }) => {
      return {
        treeData: [],
        fieldNames: {
          label: 'title',
          value: 'value',
          children: 'children',
        },
        disabled: !formModel.hospital,
        placeholder: formModel.hospital ? '请选择项目组' : '请先选择医院',
        showSearch: true,
        treeNodeFilterProp: 'title',
        getPopupContainer: () => document.body,
        dropdownStyle: { zIndex: 9999 },
        onChange: (value, label, extra) => {
          let projectName = '';
          
          if (Array.isArray(label) && label.length > 0) {
            projectName = label[label.length - 1];
          } else if (typeof label === 'string' && label) {
            projectName = label;
          }
          
          if (!projectName && extra && extra.triggerNode) {
            const node = extra.triggerNode;
            projectName = node.title || node.props?.title || node.props?.dataRef?.title || 
                         node.props?.dataRef?.departName || '';
          }
          
          if (!projectName && globalProjectTreeData && globalProjectTreeData.length > 0) {
            const findNode = (nodes, targetValue) => {
              if (!nodes || !Array.isArray(nodes)) return null;
              for (const node of nodes) {
                if (node.value === targetValue || node.key === targetValue) {
                  return node;
                }
                if (node.children && node.children.length > 0) {
                  const found = findNode(node.children, targetValue);
                  if (found) return found;
                }
              }
              return null;
            };
            
            const foundNode = findNode(globalProjectTreeData, value);
            if (foundNode) {
              projectName = foundNode.title || foundNode.departName || foundNode.label || '';
            }
          }
          
          if (projectName) {
            formActionType.setFieldsValue({ projectname: projectName });
          }
        },
      };
    },
  },
  {
    label: '项目组名字',
    field: 'projectname',
    component: 'Input',
    componentProps: {
      disabled: true,
      placeholder: '选择项目组后自动填充',
    },
  },
  {
    label: '疾病名字',
    field: 'name',
    component: 'Input',
  },
  {
    label: '疾病种类',
    field: 'type',
    component: 'Input',
  },
	// TODO 主键隐藏字段，目前写死为ID
	{
	  label: '',
	  field: 'id',
	  component: 'Input',
	  show: false
	},
];

// 高级查询数据
export const superQuerySchema = {
  idNumber: {title: '身份证',order: 0,view: 'text', type: 'string',},
  hospital: {title: '医院',order: 1,view: 'list', type: 'string',dictTable: "nurse_hospital", dictCode: 'id', dictText: 'name',},
  hospital_id: {title: '医院ID',order: 2,view: 'list', type: 'string',dictTable: "nurse_hospital", dictCode: 'id', dictText: 'name',},
  projectid: {title: '项目组id',order: 3,view: 'text', type: 'string',},
  name: {title: '疾病名字',order: 4,view: 'text', type: 'string',},
  type: {title: '疾病种类',order: 5,view: 'text', type: 'string',},
};

// 转换部门数据为树形选择器格式
function convertToTreeData(data) {
  if (!Array.isArray(data)) return [];

  return data.map((item) => {
    const nodeId = item.id || item.key || item.value;
    const nodeTitle = item.departName || item.name || item.title || item.label;

    return {
      title: nodeTitle,
      key: nodeId,
      value: nodeId,
      children: item.children && item.children.length > 0 ? convertToTreeData(item.children) : undefined,
    };
  });
}

/**
* 流程表单调用这个方法获取formSchema
* @param param
*/
export function getBpmFormSchema(_formData): FormSchema[]{
  // 默认和原始表单保持一致 如果流程中配置了权限数据，这里需要单独处理formSchema
  return formSchema;
}